package com.example.application4.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.application4.R;
import com.example.application4.database.UserDAO;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText txtUsername, txtPassword, txtPassword2, txtEmail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        txtUsername = findViewById(R.id.txtUserName);
        txtPassword = findViewById(R.id.txtPassword);
        txtPassword2 = findViewById(R.id.txtPassword2);
        txtEmail = findViewById(R.id.txtEmail);

        // 注册按钮
        Button btnRegister = findViewById(R.id.btnRegister); // 获取注册按钮
        btnRegister.setOnClickListener(this);

        // 取消按钮
        Button btnCancel = findViewById(R.id.btnCancel); // 获取取消按钮
        btnCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        // 获取用户输入的信息
        String username = txtUsername.getText().toString().trim(); // 获取并去除前后空格的用户名
        String password = txtPassword.getText().toString().trim();
        String password2 = txtPassword2.getText().toString().trim();
        String email = txtEmail.getText().toString().trim();

        if (view.getId() == R.id.btnRegister) {
            handleRegister(username, password, password2, email); // 注册逻辑
        } else if (view.getId() == R.id.btnCancel) {
            navigateToLogin(username); // 取消逻辑
        }
    }

    private void handleRegister(String username, String password, String password2, String email) {
        if (username.isEmpty() || password.isEmpty() || password2.isEmpty() || email.isEmpty()) {
            showToast("请填写所有信息");
            return;
        }

        if (!password.equals(password2)) {
            showToast("两次密码输入不一致");
            return;
        }

        // 创建 UserDAO 对象，用于数据库操作
        UserDAO userDAO = new UserDAO(RegisterActivity.this);
        long id = userDAO.insertUser(username, password, email);

        if (id == -1) {
            showToast("注册失败，您输入的用户名或邮箱已存在");
        } else {
            showToast("注册成功");
            navigateToLogin(username); // 跳转到登录页面
        }
    }

    private void navigateToLogin(String username) {
        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
        if (!username.isEmpty()) {
            Bundle bundle = new Bundle();
            bundle.putString("username", username);
            intent.putExtras(bundle);
        }
        startActivity(intent);
        finish();
    }

    private void showToast(String message) {
        Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
    }
}